/*
 * Copyright 2017-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.kover.maven.plugin.mojo.abstracts

import kotlinx.kover.maven.plugin.Constants.KOVER_REPORTS_PATH
import org.apache.maven.doxia.sink.Sink
import org.apache.maven.doxia.sink.SinkFactory
import org.apache.maven.plugins.annotations.Parameter
import org.apache.maven.reporting.MavenMultiPageReport
import org.apache.maven.reporting.MavenReport
import java.io.File
import java.util.*

/**
 * Common class for reports which can be presented as HTML and uploaded to the site.
 *
 * Actually its reports generated by `site` lifecycle.
 */
abstract class AbstractReportTaskMojo : AbstractCoverageTaskMojo(), MavenMultiPageReport {
    /**
     * Directory is configured by configuration in case of default build lifecycle
     * or through [AbstractReportTaskMojo.setReportOutputDirectory] function in case of using Maven Site Plugin.
     */
    @Parameter(defaultValue = "\${project.reporting.outputDirectory}/$KOVER_REPORTS_PATH")
    protected var outputDirectory: File = File(".")

    @Suppress("DEPRECATION")
    final override fun generate(sink: org.codehaus.doxia.sink.Sink?, locale: Locale?) {
        generate(sink, null, locale)
    }

    final override fun generate(sink: Sink?, sinkFactory: SinkFactory?, locale: Locale?) {
        if (checkKoverIsEnabled()) {
            doExecute()
        }
    }

    final override fun isExternalReport(): Boolean = true

    final override fun getCategoryName(): String = MavenReport.CATEGORY_PROJECT_REPORTS

    final override fun canGenerateReport(): Boolean = checkKoverIsEnabled()

    final override fun getReportOutputDirectory(): File = outputDirectory

    final override fun setReportOutputDirectory(outputDirectory: File?) {
        // we make sure that the reports will be in the `kover` directory
        if (outputDirectory == null) {
            this.outputDirectory = File(".")
        } else {
            this.outputDirectory = if (outputDirectory.absoluteFile.name == KOVER_REPORTS_PATH) {
                outputDirectory
            } else {
                outputDirectory.resolve(KOVER_REPORTS_PATH)
            }
        }
    }
}